package top.infopub.mgr.common.tags;


import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang3.StringUtils;

import top.infopub.generic.GenericService;
import top.infopub.util.SpringContext;

import com.alibaba.fastjson.JSON;


/**
 * easyui-combobox标签 ，采用各serviceImpl的[selectByMapWhere]方法查询数据库中的数据，形成id-name下拉列表 </br>
 * 使用示例：  </br>
 * &lt; infopub:combox id="add_partnerInfoId" name="partnerInfoId" valueField="id" textField="spartnerName" cssStyle="width: 220px;" 
 * serviceBeanId="partnerInfoServiceImpl" whereMap="type=1&state=1" dataOptions="required:true,panelHeight:'auto'" &gt; </br>
 * &lt; /infopub:combox &gt;
 * @author Awoke
 * @date 2018年10月15日
 * 
 */
public class ComboxTag extends TagSupport {

    private static final long serialVersionUID = -6996137664546485948L;

    private String id;

    private String name;

    private String value;

    private String cssClass;

    private String cssStyle;

    private String entire;

    /** 请选择后的：xx **/
    private String entireName = "";

    /** combobox 对应的value字段(bean属性，而非数据库字段)  **/
    private String valueField = "id";

    /** combobox 对应的text字段(bean属性，而非数据库字段)   **/
    private String textField;

    /** 查询方法的servicebean id  **/
    private String serviceBeanId;

    /** selectByMapWhere的查询条件 比如id=xx&name=xx **/
    private String whereMap;

    /** 附加属性，如 data-options="required:true"  **/
    private String dataOptions;
    
    /**
     * layui 是否开启验证
     */
    private String layVerify;

    /**
     * layui 增加监听事件的过滤器
     */
    private String layFilter;
    
    /**
     * layui 是否开启搜索匹配功能 true则开启
     */
    private String laySearch;
    
    /**
     * layui 是否禁用 true则开启
     */
    private String layDisabled;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public int doStartTag()
        throws JspException {

        StringBuilder sbr = new StringBuilder();
        if (StringUtils.isBlank(id)) {
            id = name;
        }
        sbr.append("<select id=\"" + id + "\" name=\"" + name + "\" ");

        if (StringUtils.isNotBlank(cssClass)) {
            sbr.append(" class=\"" + cssClass + "\" ");
        }

        if (StringUtils.isNotBlank(cssStyle)) {
            sbr.append(" style=\"" + cssStyle + "\" ");
        }

        if (StringUtils.isNotBlank(dataOptions)) {
            sbr.append(" data-options=\"" + dataOptions + "\" ");
        }
        
        if (StringUtils.isNotBlank(layVerify)) {
            sbr.append(" lay-verify=\"" + layVerify + "\" ");
        }

        if (StringUtils.isNotBlank(layFilter)) {
            sbr.append(" lay-filter=\"" + layFilter + "\" ");
        }
        
        if (StringUtils.equalsIgnoreCase("true", laySearch)) {
            sbr.append(" lay-search ");
        }
        
        if (StringUtils.equalsIgnoreCase("true", layDisabled)) {
            sbr.append(" disabled ");
        }

        sbr.append(">\n");
        if (StringUtils.equalsIgnoreCase(entire, "true") || StringUtils.isNotBlank(entireName)) {
            sbr.append("\t\t<option value=\"\">请选择" + entireName + "</option>\n");
        }

        try {
            String _v = value;

            GenericService service = SpringContext.getBean(serviceBeanId);
            // 处理where-map
            Map<String, Object> where = null;
            if (StringUtils.isNotBlank(whereMap)) {
                where = new HashMap<>();
                String[] arr = StringUtils.split(whereMap, "&");
                for (int i = 0, j = arr.length; i < j; i++ ) {
                    // k-v
                    where.put(arr[i].split("=")[0], arr[i].split("=")[1]);
                }
            }
            List queryList = service.selectByMapWhere(where);
            Iterator iterator = queryList.iterator();
            while (iterator.hasNext()) {
                String json = JSON.toJSONString(iterator.next());
                Map result = JSON.parseObject(json, HashMap.class);
                String isSelect = "";
                if (null != result) {
                    if (StringUtils.isNotBlank(_v) && result.get(valueField) != null
                        && _v.equals(result.get(valueField))) {
                        isSelect = "selected";
                    }
                    sbr.append("\t\t<option value=\"" + String.valueOf(result.get(valueField))
                               + "\" " + isSelect + ">" + result.get(textField) + "</option>\n");
                }
            }
            sbr.append("\t</select>\n");
            pageContext.getOut().write(sbr.toString());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return super.doStartTag();
    }

    @Override
    public void release() {
        super.release();
        id = "";
        name = "";
        value = "";
        cssClass = "";
        cssStyle = "";
        entire = "";
        entireName = "";
        valueField = "";
        textField = "";
        serviceBeanId = "";
        dataOptions = "";
        whereMap = "";
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getCssClass() {
        return cssClass;
    }

    public void setCssClass(String cssClass) {
        this.cssClass = cssClass;
    }

    public String getCssStyle() {
        return cssStyle;
    }

    public void setCssStyle(String cssStyle) {
        this.cssStyle = cssStyle;
    }

    public String getEntire() {
        return entire;
    }

    public void setEntire(String entire) {
        this.entire = entire;
    }

    public String getEntireName() {
        return entireName;
    }

    public void setEntireName(String entireName) {
        this.entireName = entireName;
    }

    public String getValueField() {
        return valueField;
    }

    public void setValueField(String valueField) {
        this.valueField = valueField;
    }

    public String getTextField() {
        return textField;
    }

    public void setTextField(String textField) {
        this.textField = textField;
    }

    public String getServiceBeanId() {
        return serviceBeanId;
    }

    public void setServiceBeanId(String serviceBeanId) {
        this.serviceBeanId = serviceBeanId;
    }

    public String getDataOptions() {
        return dataOptions;
    }

    public void setDataOptions(String dataOptions) {
        this.dataOptions = dataOptions;
    }

    public String getWhereMap() {
        return whereMap;
    }

    public void setWhereMap(String whereMap) {
        this.whereMap = whereMap;
    }

    public String getLayVerify() {
        return layVerify;
    }

    public void setLayVerify(String layVerify) {
        this.layVerify = layVerify;
    }

    public String getLayFilter() {
        return layFilter;
    }

    public void setLayFilter(String layFilter) {
        this.layFilter = layFilter;
    }

    public String getLaySearch() {
        return laySearch;
    }

    public void setLaySearch(String laySearch) {
        this.laySearch = laySearch;
    }

    public String getLayDisabled() {
        return layDisabled;
    }

    public void setLayDisabled(String layDisabled) {
        this.layDisabled = layDisabled;
    }

}